<template>
    <div class="bg-white" style="margin:-15px;margin-bottom:0!important">
        <!-- <el-tabs v-model='activeName'> -->
        <el-tabs v-model='preUrl' @tab-click="getList">
            <el-tab-pane label="管理员列表" name="manager">
                <div class="d-flex align-items-center">
                    <el-button type='primary' @click="openDialog('manager')">添加管理员</el-button>
                    <div class="ml-auto d-flex">
                        <el-input v-model='keyword' style="width: 200px; margin-right: 4px;"></el-input>
                        <el-button type='info' @click="getList">搜索</el-button>
                    </div>
                </div>
                <el-table :data="managerList" style="margin-top: 20px; background-color: antiquewhite; ">
                    <el-table-column label="用户头像" align="center">
                        <template slot-scope="scope">
                            <el-avatar size="large" :src="scope.row.avatar"></el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户名" align="center" prop='username'>
                    </el-table-column>
                    <!-- <el-table-column label="手机号" align="center" prop='phone'>
                    </el-table-column>
                    <el-table-column label="邮箱" align="center" prop='email'>
                    </el-table-column> -->
                    <el-table-column label="所属管理员" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.role.name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center" prop='status'>
                        <template slot-scope="scope">
                            <el-button size="mini" plain @click="changeStatus(scope.row)"
                                :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? '启用' : '禁用'
                                }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ischeck" label="操作" align="center" width="250">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-arrow" size="mini" plain
                                @click="openDialog('manager', scope.row)">
                                修改
                            </el-button>
                            <el-button type="text" icon="el-icon-arrow" size="mini" plain @click="delItem(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane label="角色列表" name="role">
                <div class="d-flex align-items-center">
                    <!-- 添加了v-auth="添加角色"之后按钮将不会在页面上展示，证明没有权限访问该节点，则不展示，具体逻辑在main.js中实现 -->
                    <el-button type='primary' v-auth="'添加角色'" @click="openDialog('role')">添加角色</el-button>
                </div>
                <el-table :data="roleList" style="margin-top: 20px; background-color: antiquewhite; ">
                    <el-table-column label="角色名称" align="center" prop='name'>
                    </el-table-column>
                    <el-table-column label="角色描述" align="center" prop='desc'>
                    </el-table-column>
                    <el-table-column label="状态" align="center" prop='status'>
                        <template slot-scope="scope">
                            <el-button size="mini" plain @click="changeStatus(scope.row)"
                                :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? '启用' : '禁用'
                                }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ischeck" label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-arrow" size="mini" plain
                                @click="openDialog('role', scope.row)">
                                修改
                            </el-button>
                            <el-button type="text" icon="el-icon-arrow" size="mini" plain
                                @click="openDrawer(scope.row)">
                                配置权限
                            </el-button>
                            <el-button type="text" icon="el-icon-arrow" size="mini" plain @click="delItem(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane label="权限列表" name="rule">
                <div class="d-flex align-items-center">
                    <!-- 添加了v-auth="添加角色"之后按钮将不会在页面上展示，证明没有权限访问该节点，则不展示，具体逻辑在main.js中实现 -->
                    <el-button type='primary' v-auth="'添加规则'" @click="openDialog('rule')">添加规则</el-button>
                </div>
                <el-tree :data="ruleList" :props="ruleProps" @node-click="handleNodeClick" default-expand-all
                    :expand-on-click-node="false">
                    <span class="custom-tree-node" slot-scope="{ data }">
                        <div>
                            <!-- 如果处于编辑状态的话就显示input框，否则就显示node.label -->
                            <!-- <el-input v-if="data.editStatus" v-model="data.label" size="mini"></el-input> -->
                            <!-- <span v-else>{{ node.label }}</span> -->
                            <!-- 如果是菜单的话就显示星星图标，不是的话就显示规则的 -->
                            <span v-if="data.menu" :class="data.icon ? data.icon : 'el-icon-star-off'"
                                class="mr-2 text-muted"></span>
                            <!-- 如果是规则的话，显示他的请求方法 -->
                            <small v-else class="mr-2 text-muted">{{ data.method }}</small>
                            <!-- <span>{{ node.label }}</span> -->
                            <span>{{ data.name }}</span>

                            <!-- 如果是的话前端就显示菜单的路径，否则就显示后端的路径 -->
                            <span class="badge" v-if="data.menu">{{ data.frontpath }}</span>
                            <span class="badge badge-secondary ml-2" v-if="data.menu">{{ data.condition }}</span>

                        </div>
                        <span>
                            <!-- <el-button size="mini" :type="data.status ? 'primary' : 'danger'"
                                @click.stop="showOrHide(data)">
                                {{ data.status ? '显示' : '隐藏' }}
                            </el-button> -->

                            <el-button size="mini" plain @click="changeStatus(data)"
                                :type="data.status ? 'success' : 'danger'">{{
                                    data.status ? '启用' : '禁用'
                                }}</el-button>
                            <el-button type="text" size="mini" @click="openDialog('rule', data.id)">
                                增加
                            </el-button>
                            <el-button :type="data.editStatus ? 'default' : 'text'" size="mini"
                                @click="openDialog('rule', data)">
                                {{ data.editStatus ? '取消编辑' : '编辑' }}
                                修改
                            </el-button>
                            <!-- <el-button type="text" size="mini" @click="remove(node, data)"> -->
                            <el-button type="text" size="mini" @click="delItem(data)">
                                删除
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </el-tab-pane>
        </el-tabs>

        <el-footer v-if="preUrl != 'rule'" class="border-top d-flex align-items-center px-0 position-fixed bg-white"
            style="bottom:0;left: 200px;right: 0; z-index: 100;">
            <!-- flex:1占剩余的所有空间 -->
            <div style="flex: 1;">
                <el-pagination :current-change="page.current" :page-sizes="page.sizes" :page-size="page.size"
                    layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </el-footer>

        <!-- 这是添加角色和管理员的模态框 -->
        <el-dialog title="添加管理员" :beforeClose="handleClose" :visible.sync="dialogVisible" width="50%">
            <!-- 这是添加角色和管理员的模态框 -->
            <el-form v-if="preUrl === 'manager'" ref="form" :model="form.manager" label-width="80px">
                <!-- 管理员 -->
                <el-form-item label="用户名">
                    <el-input v-model="form.manager.username" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="form.manager.password" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <!-- 图片选择 -->
                    <div>
                        <!-- 没有头像时显示的 -->
                        <span v-if="!form.avatar" class="btn btn-light border" @click="chooseImage">
                            <i class="el-icon-plus"></i>
                        </span>
                        <!-- 有头像时显示的 -->
                        <img v-else :src="form.manager.avatar" class="border"
                            style="width:45px;height:45px;cursor:pointer" @click="chooseImage" />
                    </div>
                </el-form-item>
                <el-form-item label="所属角色">
                    <el-select v-model="form.manager.role_id" style="height: 28px; line-height: 28px;"
                        placeholder="选择会员等级">
                        <!-- 这里的user_level是从打印出来的e即后端获取到的 -->
                        <el-option v-for="(item, index) in roleOptions" :key="index" :label="item.name"
                            :value="item.id">

                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status" size="mini">
                        <el-radio :label="1" border>启用</el-radio>
                        <el-radio :label="0" border>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <!-- 这是添加角色和修改角色的模态框 -->
            <el-form v-if="preUrl === 'role'" ref="role" :model="form.role" label-width="80px">
                <!-- 管理员 -->
                <el-form-item label="角色名称">
                    <el-input v-model="form.role.name" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="角色描述 ">
                    <el-input type="textarea" v-model="form.role.desc" size="mini"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model="form.role.status" size="mini">
                        <el-radio :label="1" border>启用</el-radio>
                        <el-radio :label="0" border>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>


            <!-- 这是添加或者修改规则的模态框 -->
            <el-form v-if="preUrl === 'rule'" ref="rule" :model="form.rule" label-width="100px">
                <el-form-item label="上级规则">
                    <el-select v-model="form.rule.rule_id" style="height: 28px; line-height: 28px;"
                        placeholder="选择上级规则">
                        <!-- 这里的user_level是从打印出来的e即后端获取到的 -->
                        <el-option label="顶级规则" value="0">

                        </el-option>
                        <!-- <el-option v-for="(item, index) in ruleOptions" :key="index" :label="item.name | tree"
                            :value="item.id"> -->
                        <el-option v-for="(item, index) in ruleOptions" :key="index" :label="item.name"
                            :value="item.id">

                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="菜单/规则">
                    <el-radio-group v-model="form.rule.menu" size="mini">
                        <el-radio :label="1" border>菜单</el-radio>
                        <el-radio :label="0" border>规则</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="名称">
                    <el-input v-model="form.rule.name" size="mini"></el-input>
                </el-form-item>

                <el-form-item label="图标" v-if="form.rule.menu">
                    <el-input v-model="form.rule.icon" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="前台路由路劲" v-if="form.rule.menu && form.rule.rule_id > 0">
                    <el-input v-model="form.rule.frontpath" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="前台路由别名" v-if="form.rule.menu">
                    <el-input v-model="form.rule.desc" size="mini"></el-input>
                </el-form-item>

                <el-form-item label="后端规则" v-if="!form.rule.menu">
                    <el-input v-model="form.rule.condition" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="请求方式" v-if="!form.rule.menu">
                    <el-select v-model="form.rule.method" style="height: 28px; line-height: 28px;" placeholder="选择请求方式">
                        <!-- 这里的user_level是从打印出来的e即后端获取到的 -->
                        <el-option label="GET" value="GET"></el-option>
                        <el-option label="POST" value="POST"></el-option>
                        <el-option label="PUT" value="PUT"></el-option>
                        <el-option label="DELETE" value="DELETE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.rule.status" size="mini">
                        <el-radio :label="1" border>启用</el-radio>
                        <el-radio :label="0" border>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 配置权限抽屉 -->
        <el-drawer title="配置权限" size="40%" :visible.sync="drawer" direction="rtl" :before-close="handleClose">
            <div style="position: absolute; top: 52px; left: 0; right: 0;bottom: 0;">
                <span>我来啦!</span>
                <div style="position: absolute; top: 0; left: 0; bottom: 60px; right: 0;">
                    <div class="bg-danger" style="overflow-y: auto;">
                        <el-tree :data="ruleList" show-checkbox node-key="id" default-expanded-all
                            :default-checked-keys="checkKeys" :props="ruleProps" :check-strictly="true"
                            @check="check">
                        </el-tree>
                    </div>
                </div>
                <div style="height: 50px; position: absolute; bottom: 0; right: 0; left: 0;"
                    class="border d-flex align-items-center justify-content-center px-3 bg-white">
                    <el-button @click="drawer = false">取 消</el-button>
                    <el-button type="primary" @click="submitRules">确 定</el-button>
                </div>
            </div>
        </el-drawer>


    </div>
</template>
<script>
import common from '@/common/mixins/common.js';


export default {
    name: 'mangerList',
    inject: ['app', 'layout'],
    mixins: [common],
    data() {
        return {
            // activeName: 'first',
            preUrl: 'manager',


            // form: {
            //     customer: '',
            //     key: '',
            // },
            managerList: [
                //     {
                //     id: '',
                //     username: '用户名',
                //     avatar: require('@/assets/image.png'),
                //     phone: '1239182433',
                //     email: '39042678@qq.com',
                //     group_id: 1,
                //     group: {
                //         id: 1,
                //         name: '管理员'
                //     },
                //     status: 1,
                // }
            ],
            keyword: '',
            roleList: [
                //     {
                //     id: '',
                //     name: '超级管理员',
                //     status: 1,
                // }
            ],
            data: [
                //     {
                //     id: 1,
                //     label: '一级 1',
                //     status: 1, //显示状态为显示
                //     editStatus: false,//是否是编辑的状态
                //     children: [{
                //         id: 2,
                //         label: '二级 1-1',
                //         status: 1, //显示状态为显示
                //         editStatus: false,//是否是编辑的状态
                //         children: [{
                //             id: 3,

                //             label: '三级 1-1-1',
                //             status: 1, //显示状态为显示
                //             editStatus: false,//是否是编辑的状态
                //         }]
                //     }]
                // }
            ],
            ruleList: [],
            ruleProps: {
                children: 'children',
                label: 'name'
            },
            dialogVisible: false, // 控制模态框的显示和隐藏
            dialogType: 'manager', // 控制模态框的类型

            dialogId: 0,// 用于编辑时的ID,默认0为添加
            form: {
                manager: {
                    username: '',
                    password: '',
                    avatar: '',
                    role_id: '',
                    status: 1, // 默认启用
                },
                role: {
                    name: '',
                    desc: '',
                    status: 1, // 默认启用
                },
                rule: {
                    menu: 0, // 是否是菜单
                    name: '',
                    rule_id: '', // 上级规则ID
                    icon: '', // 图标
                    status: '',
                    frontpath: '',
                    condition: '',
                    desc: '',
                    method: '',
                    order: 50,
                }
            },
            roleOptions: [], // 角色选项
            ruleOptions: [], // 规则选项
            role: {
                name: '',
                desc: '',
                status: 1, // 默认启用
            },

            drawerId:0,
            drawer: false,
            checkKeys: [],
        }
    },
    filters: {
        tree(item) {
            if (item.level == 0) {
                return item.name
            }
            let str = ''
            for (let i = 0; i < item.level; i++) {
                str += i == 0 ? '|--' : '--'
            }
            return str + ' ' + item.name
        }
    },
    methods: {
        // 打开弹出层模态框
        openDialog(type, item = false) {
            // 确认类型
            this.dialogType = type; // 设置模态框类型
            // 初始化表单
            switch (type) {
                case 'manager':
                    // 如果是添加管理员,item为false
                    if (!item) {
                        this.form.manager = {
                            username: '',
                            password: '',
                            avatar: '',
                            role_id: '',
                            status: 1, // 默认启用
                        };
                        this.dialogId = 0; // 添加时ID为0
                    } else {
                        // 编辑时填充数据
                        this.form.manager = {
                            username: item.username,
                            password: item.password,
                            avatar: item.avatar,
                            role_id: item.role_id,
                            status: item.status, // 启用或禁用
                        };
                        this.dialogId = item.id; // 编辑时获取ID
                    }
                    break;
                case 'role':
                    // 如果是添加管理员,item为false
                    if (!item) {
                        this.form.role = {
                            name: '',
                            desc: '',
                            status: 1, // 默认启用
                        };
                        this.dialogId = 0; // 添加时ID为0
                    } else {
                        // 编辑时填充数据
                        this.form.role = {
                            name: item.name,
                            desc: item.desc,
                            status: item.status, // 启用或禁用
                        };
                        this.dialogId = item.id; // 编辑时获取ID
                    }
                    break;

                case 'rule':
                    // 如果是添加管理员,item为false
                    if (!item || typeof item === 'number') {
                        this.form.rule = {
                            menu: 0, // 是否是菜单
                            name: '',
                            rule_id: 0, // 上级规则ID
                            icon: '', // 图标
                            status: '',
                            frontpath: '',
                            condition: '',
                            desc: '',
                            method: '',
                            order: 50,
                        };
                        this.form.rule.rule_id = item
                        this.dialogId = 0; // 添加时ID为0
                    }
                    else {
                        // 编辑时填充数据
                        this.form.rule = {
                            menu: item.menu,
                            rule_id: item.rule_id,
                            name: item.name,
                            status: item.status,
                            frontpath: item.frontpath,
                            desc: item.desc,
                            method: item.method,
                            condition: item.condition,
                            icon: item.icon,
                        };
                        this.dialogId = item.id; // 编辑时获取ID
                    }
                    break;


            }
            // 显示
            this.dialogVisible = true;
        },
        // 获取列表请求分页的url
        getListUrl() {
            if (this.preUrl === 'manager') {
                return `/admin/${this.preUrl}/${this.page.current}?limit=${this.page.size}&keyword=${this.keyword}`
            }
            return `/admin/${this.preUrl}/${this.page.current}?limit=${this.page.size}`
            // return `/admin/${this.preUrl}/${this.page.current}?limit=${this.page.size}`
        },
        getListResult(e) {
            //console.log('获取列表结果:', e);

            switch (this.preUrl) {
                case 'manager':
                    this.managerList = e.list; // 更新管理员列表
                    this.roleOptions = e.role;
                    break;
                case 'role':
                    this.roleList = e.list; // 更新角色列表

                    break;
                case 'rule':
                    this.ruleList = e.list; // 更新管理员列表
                    this.ruleOptions = e.rules; // 更新规则选项
                    break;
            }
        },
        // 关闭模态框
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(() => {
                    done();
                })
                .catch(() => { });
        },

        // 选择头像
        // 选择图片
        chooseImage() {
            // 下面的chooseImage是来自于app.vue中的函数
            // 传递max参数为3，即最大选中chooseImage=3
            this.app.chooseImage((res) => {
                // 拿到当前第一个元素的url替换掉上方的span
                // console.log(res[0].url);
                // 修改image值对应到store中的good_create.js中的sku_card.list中的image的值
                this.form.avatar = res[0].url
            }, 3);
        },

        // 提交表单
        submit() {
            this.addOrEdit(this.form[this.preUrl], this.dialogId)
            this.dialogVisible = false; // 关闭模态框
        },
        handleNodeClick() {
            // console.log(data);
        },

        openDrawer(item) {
            this.layout.showLoading()
            this.$axios.get('/admin/rule/1', {
                token: true
            }).then((res) => {
                this.drawer = true
                this.ruleList=res.data.data.list
                this.drawerId= item.id
                this.checkKeys=item.rules.map(item=>item.id)
                this.layout.hideLoading()
            }).catch(() => {
                this.layout.hideLoading()
            })
        },
        check(...e) {
            this.checkKeys = e[1].checkKeys
        },
        submitRules(){
          this.$axios.post('/admin/role/set_rules',{
            id:this.drawerId,
            rule_ids:this.checkKeys
          },{
            token:true
          }).then(()=>{
             this.drawer=false
             this.getList()
             this.$message.success('配置成功')
          }).catch(()=>{

          })
        },
        // // 树形工具的展开和不展开
        // showOrHide(data) {
        //     // 取反
        //     data.status = data.status ? 0 : 1
        // },
        // // 编辑|切换状态
        // edit(data) {
        //     data.editStatus = !data.editStatus
        // },
        // // 删除节点
        // remove(node, data) {
        //     this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(() => {
        //         // console.log(node,data);
        //         let parent = node.parent
        //         // 假如删除的是二级节点parent.data.children
        //         let children = parent.data.children || parent.data
        //         let index = children.findIndex(v => {
        //             return v.id === data.id
        //         })
        //         children.splice(index, 1)
        //     })
        // },
        // // 增加子分类
        // append(data) {
        //     let newObj = {
        //         id: 3,
        //         label: '三级 1-1-1',
        //         status: 1, //显示状态为显示
        //         editStatus: true, //是否是编辑的状态
        //         children: []
        //     }
        //     data.children.push(newObj)
        // },
        // // 拖拽完成node-drop
        // nodeDrop(...options) {
        //     console.log(options[0].data);
        //     console.log(options[1].data)
        // },
        // 添加顶级分类
        createTop() {
            this.$prompt('请输入顶级分类名称', '创建', {
                confirmButtonText: '创建',
                cancelButtonText: '取消',
                inputValidator: function (val) {
                    if (val === '' || val === null) {
                        return '分类名不能为空'
                    }
                    return true
                },
            }).then(() => {
                // console.log(value)
                // 提交服务器
            })

        }
    }
}
</script>